package com.test.util;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@SuppressWarnings("all")
@Component
public class SpringContextUtil implements ApplicationContextAware {
	Logger logger = Logger.getLogger(getClass());
	private static ApplicationContext applicationContext;
	
	/**
	 * 设置上下文环境
	 */
	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		this.applicationContext = context;
	}
	/**
	 * 获取上下文环境
	 * @return
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}
	/**
	 * 根据name获取bean
	 * @param name
	 * @return
	 * @throws BeansException
	 */
	public static Object getBean(String name) throws BeansException {
		try {
			return getApplicationContext().getBean(name);
		} catch (Exception e) {
			throw new RuntimeException("获取的Bean不存在！");
		}
	}
	/**
	 * 获取bean泛型
	 * @param name
	 * @param requiredType
	 * @return
	 * @throws BeansException
	 */
	public static <T> T getBean(String name, Class<T> requiredType)
			throws BeansException {
		return getApplicationContext().getBean(name, requiredType);
	}
	/**
	 * 是否包含某个bean
	 * @param name
	 * @return
	 */
	public static boolean containsBean(String name) {
		return getApplicationContext().containsBean(name);
	}
	/**
	 * 查询bean是否是单例模式
	 * @param name
	 * @return
	 * @throws NoSuchBeanDefinitionException
	 */
	public static boolean isSingleton(String name)	throws NoSuchBeanDefinitionException {
		return getApplicationContext().isSingleton(name);
	}
	/**
	 * 获取类型
	 * @param name
	 * @return
	 * @throws NoSuchBeanDefinitionException
	 */
	public static Class<? extends Object> getType(String name)	throws NoSuchBeanDefinitionException {
		return getApplicationContext().getType(name);
	}
	/**
	 * 获取别名数组
	 * @param name
	 * @return
	 * @throws NoSuchBeanDefinitionException
	 */
	public static String[] getAliases(String name)	throws NoSuchBeanDefinitionException {
		return getApplicationContext().getAliases(name);
	}
}
